package com.lg.controller;

import com.lg.config.RabbitConfig;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;

import static com.lg.mockpersistent.MockPersist.*;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private AmqpTemplate rabbitTemplate;

    @RequestMapping("/submit/{orderId}")
    public String submit(@PathVariable String orderId) throws UnsupportedEncodingException {

        final MessageProperties messageProperties = MessagePropertiesBuilder.newInstance().setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
                .setContentEncoding("utf-8")
                .setHeader("type", "pay")
                .setExpiration("10000")
                .build();

        final Message msg = MessageBuilder
                .withBody(orderId.getBytes("utf-8"))
                .andProperties(messageProperties)
                .build();

        rabbitTemplate.convertAndSend(RabbitConfig.EX_PAY_NORMAL, RabbitConfig.QUEUE_PAY_NORMAL, msg);

        ORDERS.put(orderId, WAITING_PAY);

        return "订单[" + orderId + "]已提交，等待支付！";
    }

    @RequestMapping("/pay/{orderId}")
    public String pay(@PathVariable String orderId) {
        String orderStatus = ORDERS.get(orderId);

        if (StringUtils.isEmpty(orderStatus)) {
            return "该订单[" + orderId + "]不存在";
        }

        if (PAY_TIMEOUT.equals(orderStatus)) {
            return "由于付款超时，该订单[" + orderId + "]已自动取消";
        }

        // 说明订单未支付超时，则修改状态为支付成功（修改时需要考虑乐观锁等操作，避免与死信队列消费者冲突）
        ORDERS.put(orderId, PAY_SUCCESS);

        return "订单[" + orderId + "]支付成功";
    }

}
